import React from "react";
import { useDispatch, useSelector } from "react-redux";
import { delByIdAction, updateByIdAction } from "../store/action";

export default function Main() {
  const { list, type } = useSelector((state) => state);
  const dispatch = useDispatch();

  // 计算属性, 不放在Redux中
  const showList = list.filter((item) => {
    // 如果type为all, 返回全部
    if (type === "all") return true;
    // 如果type为active, 返回isDone为false的
    if (type === "active") return !item.isDone;
    // 如果type为completed, 返回isDone为true的
    return item.isDone;
  });

  return (
    <section className="main">
      <input id="toggle-all" className="toggle-all" type="checkbox" />
      <label htmlFor="toggle-all">全选</label>
      <ul className="todo-list">
        {showList.map((item) => (
          <li key={item.id} className={item.isDone ? "completed" : ""}>
            <div className="view">
              <input
                checked={item.isDone}
                className="toggle"
                type="checkbox"
                onChange={() => dispatch(updateByIdAction(item.id))}
              />
              <label>{item.task}</label>
              <button
                className="destroy"
                onClick={() => dispatch(delByIdAction(item.id))}
              ></button>
            </div>
          </li>
        ))}
      </ul>
    </section>
  );
}
